//
//  STOptackViewController.m
//  YZMicroStock
//
//  Created by apple on 16/11/2.
//  Copyright © 2016年 cqjr. All rights reserved.
//

#import "YZMSTOptackViewController.h"
#import "YZMStoptackTableViewCell.h"
#import <MJRefresh.h>
#import "YZMAlertView.h"
#import "YZClient.h"
#import "YZMPageService.h"
#import "YZMStockRealModel.h"
#import "NSNumber+Utils.h"

static NSString *const stoptackcell=@"YZMStoptackTableViewCell";

@interface STOptackViewController ()<UITableViewDelegate,UITableViewDataSource>
@property(nonatomic, strong) UITableView *myListView;
@property(nonatomic, strong) NSMutableArray *datasource;
@property(nonatomic, strong) NSMutableDictionary *realDataDict;
@property (nonatomic, strong) MJRefreshNormalHeader *refreshHeader;
@property(nonatomic, strong) UIImageView *noneCellImage;
@property(nonatomic, strong) UILabel *noneCellLabel;

@end

@implementation STOptackViewController

-(NSMutableArray *)datasource{
    if (!_datasource) {
        
        _datasource=[NSMutableArray array];
    }
    return _datasource;
}

-(NSMutableDictionary *)realDataDict
{
    if (!_realDataDict) {
        
        _realDataDict=[NSMutableDictionary dictionary];
    }
    return _realDataDict;
}

- (id)init {
    if (self = [super init]) {
        self.view.backgroundColor = [YZMAppStyle appBackgroundColor];
        self.title = @"停牌策略";
        self.hidesBottomBarWhenPushed = YES;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self createObject];
    // Do any additional setup after loading the view.
}

-(void)createObject
{
    WS(ws)
    self.myListView=[[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    _myListView.backgroundColor=[YZMAppStyle appBackgroundColor];
    _myListView.separatorStyle=UITableViewCellSeparatorStyleNone;
    [_myListView registerClass:[YZMStoptackTableViewCell class] forCellReuseIdentifier:stoptackcell];
    [self.view addSubview:_myListView];
    [_myListView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(ws.view);
    }];
    _myListView.dataSource=self;
    _myListView.delegate=self;
    
    _refreshHeader = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(fetchFundListFirstPage)];
    _myListView.mj_header = _refreshHeader;

    [self fetchFundListFirstPageWithRemoveDataFlag:YES];
}


#pragma mark --refreshData'
- (void)fetchFundListFirstPage{
    
    [self fetchFundListFirstPageWithRemoveDataFlag:YES];
}

- (void)fetchFundListFirstPageWithRemoveDataFlag:(BOOL)removeFlag{
    [self getStopTackData];
}

-(void)fechFundListNextPage
{
    [self getStopTackData];
}

-(void)getStopTackData
{
    /*无网处理*/
    if (kNetworkNotReachability) {
        [self endRefresh];
        [NSError yz_showMessageForNoWifi];
        return;
    }
    
    [YZClient td_fetchTradeStopListForsuccess:^(NSURLResponse *response, id responseObject) {
        [self endRefresh];
        _myListView.mj_header=_refreshHeader;
        YZGeneralResultModel *topModel=responseObject;
        
        if (topModel.success) {
            NSArray *array=topModel.data;
            [self.datasource removeAllObjects];
            for (NSDictionary *dic in array) {
                YZMSaleTradeModel *model=(YZMSaleTradeModel *)dic;
                [self.datasource addObject:model];
            }
            if (self.datasource.count!=0) {
             
                [self getdatacode];
            } else {
                
                [self.myListView reloadData];
            }
        }else{
            if (!_datasource || self.datasource.count==0) {
                
                _myListView.mj_header=nil;
            }
            
            [topModel showMessage];
        }
        if (self.datasource.count==0) {
            [self createNoneCell];
        }
    } failure:^(NSError *error) {
        
        if (self.datasource.count==0) {
            
            _myListView.mj_header=nil;
        }
        
        [error yz_showMessage];
    }];
}

-(void)createNoneCell
{
    if (!_noneCellImage) {
        _noneCellImage=[UIImageView new];
    }
    
    [_noneCellImage setImage:[UIImage imageNamed:@"icon_no_record"]];
    [self.view addSubview:_noneCellImage];
    [_noneCellImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.width.mas_equalTo(98);
        make.centerX.mas_equalTo(self.view);
        make.top.mas_equalTo(self.view).offset(155);
    }];
    
    if (!_noneCellLabel) {
        _noneCellLabel=[YZMAppStyle labelWithLargeWhite];
    }
    _noneCellLabel.text=@"暂无数据";
    [self.view addSubview:_noneCellLabel];
    [_noneCellLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(_noneCellImage);
        make.top.mas_equalTo(_noneCellImage.mas_bottom).offset(30);
    }];
}

-(void)getdatacode
{
    NSMutableArray *array=[NSMutableArray array];
    for (YZMSaleTradeModel *model in self.datasource) {
        if (model.status<=8) {
            [array addObject:model.stockCode];
        }
    }
    if (array.count==0) {
        return;
    }
    [YZClient qt_getRealtimeInfoWithStockCodes:array success:^(NSURLResponse *response, id responseObject) {
        YZGeneralResultModel *topModel=responseObject;
        
        if (topModel.success) {
            [self.realDataDict removeAllObjects];
            [self.realDataDict addEntriesFromDictionary:topModel.data];
        }else{
            
            [topModel showMessage];
        }
        
        [self.myListView reloadData];
    } failure:^(NSError *error) {
            [error yz_showMessage];
    }];
}

- (void)endRefresh{
    if (_refreshHeader.isRefreshing) {
        [_refreshHeader endRefreshing];
    }
}

#pragma mark ---tableView

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    YZMStoptackTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:stoptackcell forIndexPath:indexPath];
    if ((indexPath.row+1)==self.datasource.count) {
        cell.islastcell=YES;
    }

    YZMSaleTradeModel *model=self.datasource[indexPath.row];
    YZMStockRealModel *recordReal = self.realDataDict[[NSString stringWithFormat:@"%@", model.stockCode]];
    [cell setvaluewithsModel:model withpModel:recordReal];
    __weak __typeof(&*self) weakSelf = self;
    cell.saleblock=^(){
        YZMAlertView *alertView=[YZMAlertView alertViewForStockSellMakeSureWithStock:model andStockReal:recordReal andClickAction:^(BOOL selectdFlag) {
            [weakSelf submitSaleTradeWithRecord:model andDelayFlag:selectdFlag];
        }];
        [alertView showInView:[YZMHCMInstance currentNavationCtroller].view];
    };

    cell.selectionStyle=UITableViewCellSelectionStyleNone;
    return cell;
}

- (void)submitSaleTradeWithRecord:(YZMSaleTradeModel *)record andDelayFlag:(BOOL)delayFlag{
    [YZClient td_closeTradeWithID:record.tid andAlwaysCloseFlag:delayFlag success:^(NSURLResponse *response, id responseObject) {
        YZGeneralResultModel *topModel = responseObject;
        if (topModel.success) {
            
            YZMSaleTradeModel *stock = [record copy];
            stock.status = YZMSaleTradeStausForToClose;
            
            [self.datasource replaceObjectAtIndex:[self.datasource indexOfObject:record] withObject:stock];
            [self.myListView reloadData];
            [MBProgressHUD showMessage:@"点卖委托成功"];
        }else{
            [topModel showMessage];
        }
    } failure:^(NSError *error) {
        [error yz_showMessage];
    }];
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    YZMSaleTradeModel *model=self.datasource[indexPath.row];
    if (model.status==8) {
        [YZMHCMInstance pushViewControllerWithName:@"stopstockDeatil" andParams:@{@"trade":model}];
    }
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.datasource.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 114;
}


-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 14;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 14;
}

-(void)buttonaction:(UIButton *)sender
{
    sender.selected=!sender.selected;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
